import store from './store'
// 引入BASE64转码编码函数/
const Base64 = require('js-base64').Base64
let Socket = ''
/**
 * 建立websocket连接
 */
// 心跳检测
var heartCheck = {
  timeout: 1000, // 1分钟发一次心跳
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function() {
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
    return this
  },
  start: function() {
    var self = this
    this.timeoutObj = setTimeout(function() {
      // 这里发送一个心跳，后端收到后，返回一个心跳消息，
      // onmessage拿到返回的心跳就说明连接正常
      Socket.send('ping')
      console.log('ping!')
      self.serverTimeoutObj = setTimeout(function() {
        // 如果超过一定时间还没重置，说明后端主动断开了
        Socket.close() // 如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
      }, self.timeout)
    }, this.timeout)
  }
}
export const createSocket = url => {
  Socket && Socket.close()
  if (!Socket) {
    console.log('建立websocket连接')
    Socket = new WebSocket(url)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
  } else {
    console.log('websocket已连接')
  }
}
export const onopenWS = () => {
  console.log('链接打开')
  heartCheck.reset().start() // 心跳检测重置
  var messageLOGIN = {
    LOGIN: {
      TOKEN: 'FEWHIFHWEIFHOQY9RR31R21FF9ML9JZH9HPH6B01',
      PRIVATE_IP: '192.168.0.205',
      PRIVATE_PORT: '62809',
      ENCODING: 'UTF-8'
    }
  }
  var messageJsonLOGIN = JSON.stringify(messageLOGIN)
  Socket.send(messageJsonLOGIN)
  var messageSHAKEHANDS = {
    'SHAKE HANDS': {
      TOKEN: 'FEWHIFHWEIFHOQY9RR31R21FF9ML9JZH9HPH6B01',
      PUBLIC_IP: '192.168.0.205',
      PUBLIC_PORT: '62809',
      ENCODING: 'UTF-8'
    }
  }
  var messageJsonSHAKEHANDS = JSON.stringify(messageSHAKEHANDS)
  Socket.send(messageJsonSHAKEHANDS)
  var messageTOKENLIST = {
    'TOKEN LIST': {
      TOKEN: 'FEWHIFHWEIFHOQY9RR31R21FF9ML9JZH9HPH6B02',
      ENCODING: 'UTF-8'
    }
  }
  var messageJsonTOKENLIST = JSON.stringify(messageTOKENLIST)
  Socket.send(messageJsonTOKENLIST)
  // public method for encoding
  var messageROUTER = {
    ROUTER: {
      TOKEN: 'FEWHIFHWEIFHOQY9RR31R21FF9ML9JZH9HPH6B01',
      'PEER TOKEN': 'FEWHIFHWEIFHOQY9RR31R21FF9ML9JZH9HPH6B02',
      CONTENT: Base64.encode('连接成功了'),
      TYPE: 'TXT',
      ENCODING: 'BASE64'
    }
  }
  var messageJsonROUTER = JSON.stringify(messageROUTER)
  Socket.send(messageJsonROUTER)
}
export const onmessageWS = e => {
  console.log(e.data)
  heartCheck.reset().start() // 心跳检测重置
  var obj = JSON.parse(e.data)
  console.log(obj)
  var sd = Base64.decode(obj.ROUTER.CONTENT)
  console.log(sd)
  if (sd === 'transaction records begin') {
    store.state.data = []
  } else if (sd === 'transaction records end') {
  } else {
    store.state.data.push(...JSON.parse(sd))
  }
}
const oncloseWS = e => {
  console.info(e)
  alert('连接没有打开，无法访问到数据！')
  console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
  console.log('closed')
}
const onerrorWS = e => {
  console.info(e)
  console.log('发生异常')
}
